<?php

	// +----------------------------------------------------------------------
	// | 私信
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace app\event\im;

	use app\common\event\Base;
	use app\model\ucenter\User as UserModel;
	use think\Db;
	use app\model\im\Chat as ChatModel;
	use app\model\im\ChatGroup as ChatGroupModel;
	use app\model\im\ChatContent as ChatContentModel;
	use app\model\im\ChatGroupContent as ChatGroupContentModel;
	use app\model\im\ChatContentRead as ChatContentReadModel;
	use think\Exception;
	use think\facade\Config;

	class ChatGroup extends Base
	{
		/**
		 * 发送者
		 * @var UserModel
		 */
		protected $user;
		/**
		 * 参数
		 * @var array
		 */
		protected $param;
		/**
		 * 接收者
		 * @var UserModel
		 */
		protected $friend;

		/**
		 * 当前发送者聊天记录
		 * @var ChatModel
		 */
		protected $userChat;
		/**
		 * 当前接受者者聊天记录
		 * @var ChatModel
		 */
		protected $friendChat;
		/**
		 * 发送的聊天内容
		 * @var ChatContentModel
		 */
		protected $content;
		protected $result;
		protected $from;

		/**
		 * 对某人的聊天框
		 * @param array $param
		 * @param UserModel $user
		 * @param JpushDevice|null $device
		 */
		public function get($param, $user = null, $device = null)
		{
			try {
				$chat = $user->chats()->where('to_user_id', $param['to_user_id'])->find();
				if (!$chat) {
					if (!is_numeric($param['to_user_id'])) {
						throw new \Exception('非法请求');
					}
					$friend = UserModel::get($param['to_user_id']);
					// TODO:用户黑名单
					if (!$friend) {
						throw new \Exception('当前用户不存在');
					}
					$chat = new ChatModel();
					$chat['to_user_id'] = $friend['id'];
					$chat['good_id'] = empty($param['good_id']) ? 0 : $param['good_id'];
					$chat = $user->chats()->save($chat);
				}
				$chat->friend;
				// 设置全部已读
				$data['data'] = $chat;
				$data['code'] = 0;
			} catch (\Exception $e) {
				$data['message'] = '用户不存在或者您无法与其对话';
				$data['code'] = 1;
			}
			return $data;
		}

		/**
		 * 设置已读
		 * @param array $param
		 * @param UserModel $user
		 */
		public function read($param, $user = null)
		{
			try {
				$chat = $user->chats()->where('status', 1)->where('is_read', 0)->update(['is_read' => 1, 'no_read_count' => 0]);

				// 设置全部已读
				$data['data'] = $chat;
				$data['code'] = 0;
			} catch (\Exception $e) {
				$data['message'] = '用户不存在或者您无法与其对话';
				$data['code'] = 1;
			}
			return $data;
		}

		/**
		 * 获取私信消息
		 * @param array $param
		 * @param UserModel $user
		 * @param null $device
		 */
		public function gets($param, $user = null, $device = null)
		{
			$chat = ChatGroupModel::where('id', 1)->find();

			if ($param['chat_min_id'])
			{
				$data['data']['lists'] = $chat->contents()->with('user')
					->where('id','<',$param['chat_min_id'])
					->where('status',1)
					->order('create_time DESC')->paginate(10);
			}else{
				$data['data']['lists'] = $chat->contents()->with('user')
					->where('status',1)
					->order('create_time DESC')->paginate(10);
			}
			$data['data']['info'] = $chat;
			$data['data']['chat_min_id'] = $chat;
			$data['code'] = 0;
			return $data;
		}

		/**
		 * 发送私信消息
		 * @param array $param
		 * @param UserModel $user
		 * @param bool $online
		 */
		public function send($param, $user, $from = 0)
		{
			try {
				$this->param = $param;
				$this->user = $user;
				$this->from = $from;
				Db::startTrans();
				// 1.判断是否用户接收消息
				$this->_checkLimit();
				// 2.创建或查询聊天记录
				$this->_setChat();
				// 3.新增内容
				$this->_createContent();
				// 4.新增阅读关联
				$this->_friendRead();
				$data['data'] = [
					'type' => 'message',
					'chat' => $this->friendChat,
					'content' => $this->content
				];
				Db::commit();
				$data['code'] = 0;
				$data['message'] = '发送成功';
			} catch (\Exception $e) {
				// 回滚事务
				Db::rollback();
				$data['code'] = 2;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}

		/**
		 * 发送群聊
		 * @param array $send
		 * @param UserModel $user
		 * @param int $from
		 * @return array
		 */
		public function sendGroup($send, $user, $from = 0)
		{
			try {
				$this->user = $user;
				$this->from = $from;
				Db::startTrans();
				// 1.查询群组
				$group = ChatGroupModel::where('id', 1)->find();

				// 3.新增内容

				$insert['content'] = $send['content'];
				$insert['ip'] = $send['ip'];
				$insert['type'] = $send['type'];
				$insert['chat_group_id'] = $group['id'];
				$insert['user_id'] = $user['id'];
				$insert['from'] = $from;
				$content = ChatGroupContentModel::create($insert);
				$group['content'] = $insert['content'];
				$group->save();
				$content['user'];
				Db::commit();
				$data['code'] = 0;
				$data['data'] = $content;
				$data['message'] = '发送成功';
			} catch (\Exception $e) {
				// 回滚事务
				Db::rollback();
				$data['code'] = 2;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}

		protected function _checkLimit()
		{
			//TODO:判断是否用户接收私信消息
			if ($this->param['to_user_id'] == $this->user['id']) {
				throw new Exception('不能发送给自己私信');
			}
		}

		protected function _setChat()
		{
			$chat = ChatModel::where('user_id', $this->user['id'])->where('to_user_id', $this->param['to_user_id'])->find();
			if ($chat) {
				$chat['new_content'] = $this->param['content'];
				$chat['message_count'] = $chat['message_count'] + 1;
				$chat['is_open'] = 1;
				$chat['last_message_time'] = time_format();
				$chat['read_time'] = time_format();
				$chat->save();
			} else {
				$chat = new ChatModel();
				$chat['user_id'] = $this->user['id'];
				$chat['new_content'] = $this->param['content'];
				$chat['to_user_id'] = $this->param['to_user_id'];
				$chat['is_read'] = 1;
				$chat['read_time'] = time_format();
				$chat['last_message_time'] = time_format();
				$chat['is_open'] = 1;
				$chat->save();
			}
			$this->userChat = $chat;
			//朋友的
			$chat = ChatModel::where('user_id', $this->param['to_user_id'])->where('to_user_id', $this->user['id'])->find();
			if ($chat) {
				$chat['new_content'] = $this->param['content'];
				$chat['no_read_count'] = $chat['no_read_count'] + 1;
				$chat['message_count'] = $chat['message_count'] + 1;
				$chat['last_message_time'] = time_format();
				$chat['is_read'] = 0;
				$chat['is_open'] = 1;
				$chat->save();
			} else {
				$chat = new ChatModel();
				$chat['new_content'] = $this->param['content'];
				$chat['no_read_count'] = 1;
				$chat['message_count'] = 1;
				$chat['last_message_time'] = time_format();
				$chat['is_read'] = 0;
				$chat['user_id'] = $this->param['to_user_id'];
				$chat['to_user_id'] = $this->user['id'];
				$chat['is_open'] = 1;
				$chat->save();
			}
			$this->friendChat = $chat;
		}

		protected function _createContent()
		{
			$this->content = new ChatContentModel;
			$this->content['content'] = $this->param['content'];
			$this->content['to_user_id'] = $this->param['to_user_id'];
			$this->content['user_id'] = $this->user['id'];
			$this->content['from'] = $this->from;
			$this->content->save();
		}

		protected function _friendRead()
		{
			$userRead = new ChatContentReadModel();
			$userRead['user_id'] = $this->user['id'];
			$userRead['chat_id'] = $this->userChat['id'];
			$userRead['to_user_id'] = $this->param['to_user_id'];
			$userRead['chat_content_id'] = $this->content['id'];
			$userRead['type'] = 0;
			$userRead['is_read'] = 1;
			$userRead['read_time'] = time_format();
			$userRead->save();
			$friendRead = new ChatContentReadModel();
			$friendRead['chat_id'] = $this->friendChat['id'];
			$friendRead['to_user_id'] = $this->user['id'];
			$friendRead['user_id'] = $this->param['to_user_id'];
			$friendRead['chat_content_id'] = $this->content['id'];
			$friendRead['type'] = 1;
			$friendRead['is_read'] = 0;
			$friendRead->save();
		}

	}
